package io.coderyeah.basic.controller;

import io.coderyeah.basic.Result;
import io.coderyeah.basic.util.FastDfsUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(value = "文件的上传和下载接口", tags = "fastDfs文件上传")
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * // @RequestPart 对复杂表单项的处理，默认name="file",与上传文件的name属性值一致
     */
    @ApiOperation("通过fastDfs文件上传到服务器")
    @PostMapping
    public Result upload(@RequestPart(value = "file", required = true) MultipartFile file) {
        // 1.截取文件后缀名 如png jpg
        final String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try {
            // 2.将图片上传服务器将文件名返回前端
            // /group1/M00/01/B2/CgAIC2Md0nWAKjOCAAQRef-xdIY168.jpg
            final String filepath = FastDfsUtils.upload(file.getBytes(), suffix);
            return Result.success(filepath,null); // 返回服务器文件路径
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败！" + e.getMessage());
        }
    }

    @ApiOperation("删除文件")
    @DeleteMapping
    public Result delete(@RequestParam("path") String path) {
        try {
            // 1.截取组名  /group1/M00/01/B2/CgAIC2Md0nWAKjOCAAQRef-xdIY168.jpg
            // 1.1临时路径
            final String tempPath = path.substring(1); // group1/M00/01/B2/CgAIC2Md0nWAKjOCAAQRef-xdIY168.jpg
            final String groupName = tempPath.substring(0, tempPath.indexOf("/")); // group1
            System.out.println(tempPath);
            System.out.println(groupName);
            // 2.远程路径
            final String remotePath = tempPath.substring(tempPath.indexOf("/") + 1);
            FastDfsUtils.delete(groupName, remotePath);
            return Result.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("删除失败" + e.getMessage());
        }
    }
}
